package com.edt.ichannel.utils;

import cc.edt.iceutils2.string.IceStringUtils;
import com.edt.ichannel.utils.entity.FtpResult;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.*;
import java.net.SocketException;
import java.util.*;

public class FtpUtil {

    private static Logger logger = LogManager.getLogger(FtpUtil.class);

    private FtpUtil() {
    }

    private static FTPClient getFTPClient(String ftpHost, String ftpPassword, String ftpUserName, int ftpPort) {
        FTPClient ftpClient = null;

        try {
            ftpClient = new FTPClient();
            ftpClient.connect(ftpHost, ftpPort);
            ftpClient.login(ftpUserName, ftpPassword);
            logger.info("userName:"+ftpUserName);
            logger.info("ftpPassword:"+ftpPassword);
            logger.info("ftpHost:"+ftpHost);
            logger.info("ftpPort:"+ftpPort);
            logger.info("replycode:"+ftpClient.getReplyCode());
            logger.info("replyStr:"+ftpClient.getReplyString());
            if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
                logger.error("未连接到FTP，用户名或密码错误。");
                ftpClient.disconnect();
            } else {
                logger.info("FTP连接成功。");
            }
        } catch (SocketException var6) {
            var6.printStackTrace();
            logger.info("FTP的IP地址可能错误，请正确配置。");
        } catch (IOException var7) {
            var7.printStackTrace();
            logger.error("FTP的端口错误,请正确配置。");
        }

        return ftpClient;
    }

    public static FtpResult readFile(String ftpHost, String ftpPassword, String ftpUserName, int ftpPort, String ftpPath, String fileName, String charSet) {
        FtpResult ftpUtilsResult = new FtpResult();
        Set<String> strSet = new LinkedHashSet<>() ;
        FileInputStream inFile = null;
        InputStream in = null;
        FTPClient ftpClient = null;
        logger.info("开始读取绝对路径：" + ftpPath +"/"+fileName+ "文件!");
        logger.info("文件名：" + fileName);
        try {
            ftpClient = getFTPClient(ftpHost, ftpPassword, ftpUserName, ftpPort);
            ftpClient.setControlEncoding(charSet);
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            ftpClient.enterLocalPassiveMode();
//            ftpClient.enterLocalActiveMode();
            ftpPath = new String(ftpPath.getBytes(charSet), "iso-8859-1");
            ftpClient.changeWorkingDirectory(ftpPath);
            fileName = new String(fileName.getBytes(charSet), "iso-8859-1");
            in = ftpClient.retrieveFileStream(fileName);
        } catch (FileNotFoundException var27) {
            var27.printStackTrace();
            ftpUtilsResult.setSuccess(false);
            ftpUtilsResult.setMessage("没有找到文件:"+fileName);
            logger.error(var27.getMessage());
            logger.error("--->没有找到文件:"+fileName);
            return ftpUtilsResult;
        } catch (SocketException var28) {
            var28.printStackTrace();
            ftpUtilsResult.setSuccess(false);
            ftpUtilsResult.setMessage("FTP连接失败");
            logger.error(var28.getMessage());
            return ftpUtilsResult;
        } catch (IOException var29) {
            var29.printStackTrace();
            ftpUtilsResult.setSuccess(false);
            ftpUtilsResult.setMessage("文件读取错误");
            logger.error(var29.getMessage());
            return ftpUtilsResult;
        }

        if (in == null) {
            ftpUtilsResult.setSuccess(false);
            ftpUtilsResult.setMessage("没有找到" + ftpPath +"/"+fileName+ "文件");
            logger.error(ftpUtilsResult.getMessage());
            return ftpUtilsResult;
        } else {
            BufferedReader br = null;
            try {
                br = new BufferedReader(new InputStreamReader(in,charSet));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            String data = null;

            label102: {
                FtpResult var14;
                try {
                    while(true) {
                        if ((data = br.readLine()) == null) {
                            break label102;
                        }
                        if(IceStringUtils.isNoneBlank(data)){
                            strSet.add(data);
                        }

                    }

                } catch (IOException var30) {
//                    var30.printStackTrace();
                    ftpUtilsResult.setSuccess(false);
                    ftpUtilsResult.setMessage("文件内容读取错误");
                    logger.error(var30.getMessage());
                    var14 = ftpUtilsResult;
                } finally {
                    try {
                        ftpClient.disconnect();
                    } catch (IOException var26) {
                        var26.printStackTrace();
                    }

                }

                return var14;
            }

            ftpUtilsResult.setSuccess(true);
            ftpUtilsResult.setResultSet(strSet);
            ftpUtilsResult.setMessage("读取成功");
            return ftpUtilsResult;
        }
    }

    public static List<String> getFileNames(String ftpHost, String ftpPassword, String ftpUserName, int ftpPort, String ftpPath, String charSet) {
        FTPClient ftpClient = null;
        logger.info("开始读取绝对路径" + ftpPath + "文件!");

        try{
            ftpClient = getFTPClient(ftpHost, ftpPassword, ftpUserName, ftpPort);
            ftpClient.setControlEncoding(charSet);
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            ftpClient.enterLocalPassiveMode();
            ftpPath = new String(ftpPath.getBytes(charSet), "iso-8859-1");
            ftpClient.changeWorkingDirectory(ftpPath);
            FTPFile[] files = ftpClient.listFiles(ftpPath);
            List<String> fileNames = new ArrayList<>();
            for (FTPFile file : files) {
                fileNames.add(file.getName());
            }
            return fileNames;
        }catch (Exception e){
            e.getStackTrace();
            return null;
        }finally {
            try {
                assert ftpClient != null;
                ftpClient.disconnect();
            } catch (IOException var26) {
                var26.printStackTrace();
            }

        }

    }
    /**
     * Description: 从FTP服务器下载文件
     * @return ftpresult
     */
    public static FtpResult downloadFile(String ftpHost, String ftpPassword, String ftpUserName, int ftpPort, String ftpPath, String fileName,String localPath,String localName) {
        FtpResult result = new FtpResult();
        FTPClient ftpClient = null;
        try {
            ftpClient = getFTPClient(ftpHost, ftpPassword, ftpUserName, ftpPort);
//            ftpClient.setControlEncoding(charSet);
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            ftpClient.enterLocalPassiveMode();
//            ftpPath = new String(ftpPath.getBytes(charSet), "iso-8859-1");
//            fileName = new String(fileName.getBytes(charSet), "iso-8859-1");
            ftpClient.changeWorkingDirectory(ftpPath);//转移到FTP服务器目录
            FTPFile[] fs = ftpClient.listFiles();
            for(FTPFile ff:fs){
                if(ff.getName().equals(fileName)){
                    File localFile = new File(localPath+"/"+localName);
                    OutputStream is = new FileOutputStream(localFile);
                    ftpClient.retrieveFile(ff.getName(), is);
                    is.close();
                }
            }
            ftpClient.logout();
            result.setSuccess(true);
            result.setMessage("下载成功："+localPath+"/"+localName);
            return result;
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage("下载失败"+e.getMessage());
            logger.error(e.getMessage());
            return  result;
        } finally {
            assert ftpClient != null;
            if (ftpClient.isConnected()) {
                try {
                    ftpClient.disconnect();
                } catch (IOException ignored) {
                }
            }
        }
    }


    public static void uploadFile(String ftpHost, String ftpPassword, String ftpUserName, int ftpPort, String ftpPath, String ftpFileName, String fileContent, String writeTempFielPath) {
        FTPClient ftpClient = null;
        logger.info("开始上传文件到FTP.");

        try {
            ftpClient = getFTPClient(ftpHost, ftpPassword, ftpUserName, ftpPort);
            ftpClient.enterLocalPassiveMode();
            ftpClient.setFileType(2);
            boolean writeResult = FileUtil.write(ftpFileName, fileContent, writeTempFielPath);
            if (writeResult) {
                ftpPath = new String(ftpPath.getBytes("UTF-8"), "iso-8859-1");
                ftpClient.changeWorkingDirectory(ftpPath);
                File f = new File(writeTempFielPath + "/" + ftpFileName);
                InputStream in = new FileInputStream(f);
                String uploadFtpFileName = new String(ftpFileName.getBytes("UTF-8"), "iso-8859-1");
                ftpClient.storeFile(uploadFtpFileName, in);
                in.close();
                logger.info("上传文件" + ftpFileName + "到FTP成功!");
                f.delete();
            } else {
                logger.info("写文件失败!");
            }
        } catch (Exception var21) {
            var21.printStackTrace();
        } finally {
            try {
                if (ftpClient != null) {
                    ftpClient.disconnect();
                }
            } catch (IOException var20) {
                var20.printStackTrace();
            }

        }

    }

    public static void uploadFileAndSaveTemp(String ftpHost, String ftpPassword, String ftpUserName, int ftpPort, String ftpPath, String ftpFileName, String fileContent, String writeTempFielPath) {
        FTPClient ftpClient = null;
        logger.info("开始上传文件到FTP.");

        try {
            boolean writeResult = FileUtil.write(ftpFileName, fileContent, writeTempFielPath);
            ftpClient = getFTPClient(ftpHost, ftpPassword, ftpUserName, ftpPort);
            ftpClient.enterLocalPassiveMode();
            ftpClient.setFileType(2);
            if (writeResult) {
                ftpPath = new String(ftpPath.getBytes("UTF-8"), "iso-8859-1");
                ftpClient.changeWorkingDirectory(ftpPath);
                File f = new File(writeTempFielPath + "/" + ftpFileName);
                InputStream in = new FileInputStream(f);
                String uploadFtpFileName = new String(ftpFileName.getBytes("UTF-8"), "iso-8859-1");
                ftpClient.storeFile(uploadFtpFileName, in);
                in.close();
                logger.info("上传文件" + ftpFileName + "到FTP成功!");
            } else {
                logger.info("写文件失败!");
            }
        } catch (Exception var21) {
            var21.printStackTrace();
        } finally {
            try {
                if (ftpClient != null) {
                    ftpClient.disconnect();
                }
            } catch (IOException var20) {
                var20.printStackTrace();
            }

        }

    }


    public static void uploadFileAndSaveTempByInitiative(String ftpHost, String ftpPassword, String ftpUserName, int ftpPort, String ftpPath, String ftpFileName, String fileContent, String writeTempFielPath) {
        FTPClient ftpClient = null;
        logger.info("开始上传文件到FTP.");

        try {
            boolean writeResult = FileUtil.write(ftpFileName, fileContent, writeTempFielPath);
            ftpClient = getFTPClient(ftpHost, ftpPassword, ftpUserName, ftpPort);
            ftpClient.enterLocalActiveMode();
            ftpClient.setFileType(2);
            if (writeResult) {
                ftpPath = new String(ftpPath.getBytes("UTF-8"), "iso-8859-1");
                ftpClient.changeWorkingDirectory(ftpPath);
                File f = new File(writeTempFielPath + "/" + ftpFileName);
                InputStream in = new FileInputStream(f);
                String uploadFtpFileName = new String(ftpFileName.getBytes("UTF-8"), "iso-8859-1");
                ftpClient.storeFile(uploadFtpFileName, in);
                in.close();
                logger.info("上传文件" + ftpFileName + "到FTP成功!");
            } else {
                logger.info("写文件失败!");
            }
        } catch (Exception var21) {
            var21.printStackTrace();
        } finally {
            try {
                if (ftpClient != null) {
                    ftpClient.disconnect();
                }
            } catch (IOException var20) {
                var20.printStackTrace();
            }

        }
    }
}
